#!/usr/bin/env python
# -*- coding:utf8 -*-
"""
Author : mafei
Date   : 2019-12-07
"""
import time
import logging
import coreapi
import coreschema
from mmonitor.models.mysql_db import UserModel, ErrorHistoryModel, WebSiteModel
from .base import ViewBase
from mmonitor.utils.validator import is_uuid4
from mmonitor.common.vars import attack_msg, http_error_dict
from mmonitor.utils.change_time import change_time


class AlertHistory(ViewBase):
    get_fields = (
        coreapi.Field(
            name='url_id',
            location='query',
            description=u'web url_id',
            required=True,
            type="String",
            schema=coreschema.String()
        ),
    )

    def get(self, request):
        user_id = request.session["user"]
        url_id = request.qget_string("url_id", "")
        start_time = request.qget_int("start_time", int(time.time()) -1000*60*60*24*7)
        end_time = request.qget_int("end_time", int(time.time()*1000))
        if not is_uuid4(user_id) or (url_id and not is_uuid4(url_id)):
            return self.error_response(attack_msg)
        user = UserModel.get_or_none(UserModel.user_id == user_id)
        if not user:
            return self.error_response("用户丢了")
        if not url_id:
            res = WebSiteModel.get_or_none(WebSiteModel.user_id == user.id)
            if not res:
                return self.error_response("还没有监控项呢，可以去加一个!")
            url_id = res.id
        else:
            url = WebSiteModel.get_or_none((WebSiteModel.url_id == url_id))
            if not url:
                return self.error_response("url不存在!")
            url_id = url.id
        url_data = ErrorHistoryModel.select().where(ErrorHistoryModel.item_id == url_id)
        # url_data = url_data.where(ts__gt=start_time)
        url_data = url_data.where(ErrorHistoryModel.start_time.between(start_time, end_time)).order_by(ErrorHistoryModel.start_time.desc())

        result = []
        for u in url_data:
            keep_ts = change_time(u.update_time - u.start_time)

            if keep_ts == 0:
                keep_ts = change_time(int(time.time()*1000) - u.start_time)
            d = u.to_dict()
            d['keep_ts'] = keep_ts
            d['error'] = http_error_dict[d['error']]
            result.append(d)
        return self.ok_response(result)

    def post(self, request):

        return self.ok_response()

    def put(self, request):

        return self.ok_response()

    def delete(self, request):

        return self.ok_response()
